// audit.statics.js
$(function() {
    // 初始化日期选择器显示控制
    $('#timeRangeFilter').change(function() {
        if ($(this).val() === 'custom') {
            $('#dateRangePicker').show();
        } else {
            $('#dateRangePicker').hide();
            loadStatisticsData();
        }
    });

    // 刷新数据按钮事件
    $('#refreshData').click(function() {
        $(this).html('<i class="fa fa-spinner fa-spin mr-1"></i> 加载中...');
        loadStatisticsData().finally(() => {
            $(this).html('<i class="fa fa-refresh mr-1"></i> 刷新数据');
        });
    });

    // 导出报表按钮事件
    $('#exportData').click(function() {
        const params = getRequestParams();
        // 构建导出URL
        const exportUrl = `/static/exportData?${$.param(params)}`;
        window.open(exportUrl, '_blank');
    });

    // 图表周期切换事件
    $('.chart-period-btn').click(function() {
        $('.chart-period-btn').removeClass('bg-primary/10 text-primary').addClass('bg-neutral-100 text-neutral-500');
        $(this).removeClass('bg-neutral-100 text-neutral-500').addClass('bg-primary/10 text-primary');
        loadAuditTrendChart($(this).data('period'));
    });

    // 审核员统计类型切换事件
    $('#auditorStatType').change(function() {
        loadAuditorStatsTable($(this).val());
    });

    // 内容类型筛选事件
    $('#contentTypeFilter').change(function() {
        loadStatisticsData();
    });

    // 初始化页面数据
    function init() {
        initCharts();
        loadStatisticsData();
        loadAuditorStatsTable('completed');
    }

    // 获取请求参数
    function getRequestParams() {
        const timeRange = $('#timeRangeFilter').val();
        const contentType = $('#contentTypeFilter').val();
        let startDate = $('#startDate').val();
        let endDate = $('#endDate').val();

        return {
            timeRange,
            contentType,
            startDate: timeRange === 'custom' ? startDate : '',
            endDate: timeRange === 'custom' ? endDate : '',
        };
    }

    // 加载统计数据
    function loadStatisticsData() {
        const params = getRequestParams();
        
        return Promise.all([
            // 并行请求各类数据
            $.getJSON('/static/getAuditResultDistribution', params),
            $.getJSON('/static/getContentTypeDistribution', params),
            $.getJSON('/static/getSensitiveTypeDistribution', params)
        ]).then(([resultDist, typeDist, sensitiveDist]) => {
            // 处理审核结果分布数据
            if (resultDist.status/1 == 0) {                
                updateCoreStats(resultDist.data);
                updateAuditResultChart(resultDist.data);
            }

            // 处理内容类型分布数据
            if (typeDist.status/1 == 0) {
                updateContentTypeChart(typeDist.data);
            }

            // 处理敏感内容分布数据
            if (sensitiveDist.status/1 == 0) {
                updateSensitiveTypeChart(sensitiveDist.data);
            }

            // 刷新趋势图
            const period = $('#dayBtn').data('period') || 'day';
            loadAuditTrendChart(period);

        }).catch(error => {
            console.error('数据加载失败:', error);
            alert('数据加载失败，请重试');
        });
    }

    // 初始化图表
    function initCharts() {
        // 审核趋势图
        window.auditTrendChart = new Chart($('#auditTrendChart'), {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '审核总量',
                    data: [],
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.3,
                    fill: true
                }]
            },
            options: getChartOptions('审核量趋势')
        });

        // 审核结果分布图
        window.auditResultPieChart = new Chart($('#auditResultPieChart'), {
            type: 'doughnut',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: ['#10b981', '#ef4444', '#f59e0b', '#6366f1'],
                    borderWidth: 0
                }]
            },
            options: getPieChartOptions()
        });

        // 内容类型分布图
        window.contentTypePieChart = new Chart($('#contentTypePieChart'), {
            type: 'pie',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: ['#3b82f6', '#8b5cf6', '#ec4899', '#10b981', '#f59e0b'],
                    borderWidth: 0
                }]
            },
            options: getPieChartOptions()
        });

        // 敏感内容类型分布图
        window.sensitiveTypeChart = new Chart($('#sensitiveTypeChart'), {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '敏感内容数量',
                    data: [],
                    backgroundColor: '#ef4444'
                }]
            },
            options: getChartOptions('敏感内容类型分布')
        });
    }

    // 加载审核趋势图
    function loadAuditTrendChart(period) {
        const params = {
            ...getRequestParams(),
            period
        };

        $.getJSON('/static/getAuditTrend', params)
            .done(function(result) {
                if (result.status/1 == 0) {
                    window.auditTrendChart.data.labels = result.data.time_nodes;
                    window.auditTrendChart.data.datasets[0].data = result.data.audit_counts;
                    window.auditTrendChart.update();
                }
            })
            .fail(function() {
                console.error('审核趋势数据加载失败');
            });
    }

    // 加载审核员统计表格
    function loadAuditorStatsTable(type) {
        const params = {
            ...getRequestParams(),
            page: 1,
            pageSize: 10
        };

        $.getJSON('/static/getAuditorPerformance', params)
            .done(function(result) {
                if (result.status/1 == 0) {
                    let auditors = result.data.list;
                    
                    // 根据类型排序
                    switch(type) {
                        case 'completed':
                            auditors.sort((a, b) => b.completed - a.completed);
                            break;
                        case 'speed':
                            auditors.sort((a, b) => a.avg_process_time - b.avg_process_time);
                            break;
                        case 'accuracy':
                            auditors.sort((a, b) => parseFloat(b.accuracy) - parseFloat(a.accuracy));
                            break;
                    }

                    // 填充表格
                    let html = '';
                    auditors.forEach((auditor, index) => {
                        html += `
                        <tr>
                            <td class="px-5 py-4">${index + 1}</td>
                            <td class="px-5 py-4">${auditor.auditor_name}</td>
                            <td class="px-5 py-4">${auditor.completed}</td>
                            <td class="px-5 py-4">${auditor.passed}</td>
                            <td class="px-5 py-4">${auditor.rejected}</td>
                            <td class="px-5 py-4">${auditor.avg_process_time} 分钟</td>
                            <td class="px-5 py-4">${auditor.accuracy}</td>
                        </tr>
                        `;
                    });
                    $('#auditorStatsTableBody').html(html);
                }
            })
            .fail(function() {
                console.error('审核员数据加载失败');
            });
    }

    // 更新核心统计指标
    function updateCoreStats(data) {
        let total = 0;
        let approved = 0;
        let rejected = 0;

        data.forEach(item => {
            total += item.value;
            
            switch(item.name) {
                case '审核通过':
                    approved = item.value;
                    break;
                case '审核拒绝':
                    rejected = item.value;
                    break;
            }
        });

        $('#totalAuditCount').text(formatNumber(total));
        $('#approvedCount').text(formatNumber(approved));
        $('#rejectedCount').text(formatNumber(rejected));
    }

    // 更新审核结果分布图表
    function updateAuditResultChart(data) {
        window.auditResultPieChart.data.labels = data.map(item => item.name);
        window.auditResultPieChart.data.datasets[0].data = data.map(item => item.value);
        window.auditResultPieChart.update();
    }

    // 更新内容类型分布图表
    function updateContentTypeChart(data) {
        window.contentTypePieChart.data.labels = data.map(item => item.name);
        window.contentTypePieChart.data.datasets[0].data = data.map(item => item.value);
        window.contentTypePieChart.update();
    }

    // 更新敏感内容类型分布图表
    function updateSensitiveTypeChart(data) {
        window.sensitiveTypeChart.data.labels = data.map(item => item.name);
        window.sensitiveTypeChart.data.datasets[0].data = data.map(item => item.value);
        window.sensitiveTypeChart.update();
    }

    // 获取图表通用配置
    function getChartOptions(title) {
        return {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        };
    }

    // 获取饼图配置
    function getPieChartOptions() {
        return {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                }
            },
            cutout: '65%'
        };
    }

    // 格式化数字为带千分位的格式
    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    // 页面加载完成后初始化
    init();
});